var admin_index = new Object();

admin_index.page;
admin_index.page1;
admin_index.page_size = 10;
admin_index.page_size1 = 11
admin_index.obj;
admin_index.pageNum = 1;
admin_index.project_status = $("#project_status").val();
admin_index.deptId = $("#deptId").val();
admin_index.public_list_show = true;
admin_index.init = function (page_, page1_) {
    admin_index.page = page_;
    admin_index.page1 = page1_;
    admin_index.initTable();
    $("#public_box").hide();
    admin_index.initTable_public();
    //显示项目状态
    admin_index.show_project_status();
    //初始化单位统计信息
    admin_index.getSubjects(admin_index.pageNum);
    // 初始化
    admin_index.click();

    admin_index.handlerPublish();
    // 政策须知
    admin_index.trainPolicyNotes();

    admin_index.trainWarnNotes();
}

admin_index.show_project_status = function () {
    $("span[project_status='" + admin_index.project_status + "']").siblings().removeClass("active");
    $("span[project_status='" + admin_index.project_status + "']").addClass("active");
}

//主题展示
admin_index.getSubjects = function (pageNum) {
    var url = appPath + "/admin/train_subject/subject_list";
    if (pageNum) {
        admin_index.pageNum = pageNum;
    }
    var params = {
        'pageSize': admin_index.page_size1,
        'pageNum': admin_index.pageNum
    };
    $.ajax({
        url: url,
        data: params,
        type: "post",
        dataType: "json",
        success: function (rs) {
            var data = rs['result'];
            var dataList = data['dataList'];
            //var length = $("#subjects").parent().find("th").length;
            /*if(dataList.length<1){
                $("#"+_this.tbody_id).empty().html(_this.noList(length));$("#"+_this.page_id).empty();return
            }*/
            var inner = admin_index.list(dataList);

            // 计算分页
            var page = data['page']; // 当前页数
            var pageSize = data['pageSize']; // 每页数量
            var count = data['count']; // 总条数
            var totalPages = data['totalPages']; // 总页数
            var haveNext = data['haveNext']; // 是否有下一页
            var nextPage = data['nextPage']; // 下一页页数
            var havePre = data['havePre']; // 是否有上一页
            var prePage = data['prePage']; // 上一页页数

            if (page == 1) {
                inner += "<a href='javascript:;' class='left icon_btn' style='display: none;'>左按钮</a>";
            } else {
                inner += "<a href='javascript:;' class='left icon_btn'>左按钮</a>";
            }
            if (havePre == 0) {
                inner += "<a href='javascript:;' class='left icon_btn' style='display: none;'>左按钮 </a>";
            } else {
                inner += "<a href=\"javascript:admin_index.getSubjects(" + (page - 1) + ");\" class='left icon_btn'>左按钮 </a>";
            }
            if (haveNext == 1) {
                inner += "<a href=\"javascript:admin_index.getSubjects(" + (page + 1) + ");\" class='right icon_btn'>右按钮 </a>";
            } else {
                inner += "<a  class='right icon_btn' style='display: none;'>右按钮  </a>";
            }
            //console.log(inner)
            // 渲染表单
            $(".list_container").empty().html(inner);

        }
    });
}

admin_index.list = function (dataList) {
    var len = dataList.length;
    var inner = "<ul class='clearfix'>", item;
    inner += '<li class="first">' +
        '<div class="show_img">' +
        '<img src="' + appPath + '/static/global/images/v2/no-project.png" alt="">' +
        /*'<span class="enter">点击进入</span>'+*/
        /*'<div class="show_div">' +
            '<div class="show_div_bg"></div>' +
        '</div>'+*/

        /*'<p>无主题<span class="show_line"></span></p>' +*/
        '</div>' +
        '<div class="title">' +
        '<img src="' + appPath + '/static/global/images/v2/title_info_icon.png" alt="">' +
        '<div class="title_1"><b>从业人员<i>自定义培训</i></b></div>' +
        '<div class="title_2">(您可以在此自定义培训内容)</div>' +
        '</div>' +
        '<div class="create">' +
        '<div class="options">' +
        '<div class="option" data-projectdId="1" onclick="admin_index.select(this)"><span>TRAINING</span>培训</div>' +
        '<div class="option" data-projectdId="2" onclick="admin_index.select(this)"><span>EXERCISE</span>练习</div>' +
        '<div class="option" data-projectdId="3" onclick="admin_index.select(this)"><span>EXAM</span>考试</div>' +
        '</div>' +
        '<button class="create_btn" id="btn_project_create" onclick="admin_index.createProject(this)">创建</button>' +
        '</div>' +
        "</li>";


    // 组装数据
    for (var i = 0; i < len; i++) {
        item = dataList[i];
        if (null == item.varSubjectDesc) {
            item.varSubjectDesc = ""
        }
        var temp_logo = appPath + "/static/global/images/subject_image/subject_image_" + parseInt(Math.round(Math.random())) + ".png";
        /*if("" == item.logo){
            item.logo = appPath + "/static/global/images/subject_image/subject_image_"+ parseInt(Math.round(Math.random())) +".png";
        }*/
        inner += '<li>' +
            '<div class="show_img">' +
            '<img alt="" class="lazy lazy_img" src="' + item.logo + '" onerror="admin_index.imgError(this)" >' +

            /*'<div class="show_div">' +
              '<div class="show_div_bg"></div>' +

                '<p>'+item.subjectDesc+'<span class="show_line"></span></p></div>'+*/

            '</div>' +
            '<div class="title">' + item.varSubjectName + '</div>' +
            '<div class="create">' +
            '<div class="options">' +
            '<div class="option" data-projectdId="1" onclick="admin_index.select(this)"><span>TRAINING</span>培训</div>' +
            '<div class="option" data-projectdId="2" onclick="admin_index.select(this)"><span>EXERCISE</span>练习</div>' +
            '<div class="option" data-projectdId="3" onclick="admin_index.select(this)"><span>EXAM</span>考试</div>' +
            '</div>' +
            '<button class="create_btn" id="btn_project_create" data-subjectId="' + item.intTrainSubjectId + '" data-subjectName="' + item.varSubjectName + '" onclick="admin_index.createProject(this)" >创建</button>' +
            '</div>' +
            "</li>";
    }
    inner += '<script>' +
        '$("img.lazy").lazyload({effect: "fadeIn"});' +
        '</script>'
    inner += "</ul>"
    //console.log(inner)
    return inner;

}

admin_index.select = function (obj) {
    var $this = $(obj);
    $this.toggleClass("active");
}
admin_index.imgError = function (obj) {
    var temp_logo = appPath + "/static/global/images/subject_image/subject_image_" + parseInt(Math.round(Math.random())) + ".png";
    $(obj).attr('src', temp_logo);
}

//首页统计信息
admin_index.statistics = function () {
    $.ajax({
        url: appPath + "/admin/tongJi",
        type: 'post',
        success: function (data) {
            $("#countUser").text(data.countUser);
            $("#countTrainUser").text(data.countTrainUser);
            $("#percentTrainComplete").text(data.percentTrainComplete + "%");
            $("#countCourse").text(data.countCourse);
            $("#countQuestion").text(data.countQuestion);
            $("#countProject").text(data.countProject);
            $("#totalClassHour").text(data.totalClassHour);
            $("#averagePersonClassHour").text(data.averagePersonClassHour);
            $("#totalYearClassHour").text(data.totalYearClassHour);
            $("#averageYearClassHour").text(data.averageYearClassHour);
            $("#countTrain").text(data.countTrain);
            $("#countTrainCompleteYes").text(data.countTrain);
            $("#countExam").text(data.countTrain);
            $("#countExamPassYes").text(data.countTrain);
        }

    })
}

//创建项目 (取项目类型和主题编号)
admin_index.createProject = function (obj) {
    var $div = $(obj).prev().find(".active")
    var projectTypeNo = "";
    var array = [];
    $($div).each(function (index, element) {
        var str = $(this).attr("data-projectdId");
        array.push(str);

    })

    if (array.length != 0) {
        //项目类型 1：培训/2：练习/3：考试/4：培训-练习/5：培训-考试/6：练习，考试/7：培训，练习，考试

        if (array.length == 1) {
            for (var i = 0; i < array.length; i++) {
                if (array[i] == 1) {
                    projectTypeNo = "1";
                } else if (array[i] == 2) {
                    projectTypeNo = "2";
                } else {
                    projectTypeNo = "3";
                }
            }
        }

        if (array.length == 2) {
            if (array[0] == 1 && array[1] == 2) {
                projectTypeNo = "4";
            } else if (array[0] == 1 && array[1] == 3) {
                projectTypeNo = "5";
            } else {
                projectTypeNo = "6";
            }
        }
        if (array.length == 3) {
            projectTypeNo = "7";
        }

        // 项目主题编号
        var subjectId = $(obj).attr("data-subjectId");
        if (subjectId == "" || subjectId == undefined) {
            subjectId = "";
        }
        var subjectName = $(obj).attr("data-subjectName");
        if (subjectName == "" || subjectName == undefined) {
            subjectName = "";
        }
        window.location.href = appPath + "/admin/project_create/private/create_private_project?projectTypeNo=" + projectTypeNo + "&subjectId=" + subjectId + "&subjectName=" + subjectName;
    } else {
        layer.msg("请选择培训类别");
    }

    //})

};

/**
 * 企业项目列表
 */
admin_index.initTable = function () {
    var list_url = appPath + "/admin/project_private/list";
    admin_index.page.init("private_project_form", list_url, "private_project_list", "private_project_page", 1, admin_index.page_size);
    admin_index.page.goPage(1);
    admin_index.page.list = function (dataList) {//console.log(dataList)
        var inner = "", item;
        admin_index.obj = dataList;
        var len = dataList.length;
        var permissionList =$("#permissionList").val();
        // 组装数据
        for (var i = 0; i < len; i++) {
            item = dataList[i];
            inner += "<tr>";
            inner += "<td>" + (i + 1) + "</td>";
            inner += "<td id=\'pan_varProjectName + item['id']\'><span class=\"tooltip\" data-length='20'>" + item['project_name'] + "</span></td>";
            inner += "<td>" + Enum.projectType(item['project_type']) + "</td>";

            var projectType = item['project_type'];
            /*if(projectType == '3'){
                inner += '<td>'+ TimeUtil.longMsTimeToDateTime3(item['project_start_time']) + '<br/>' + TimeUtil.longMsTimeToDateTime3(item['project_end_time']) + '</td>';
            }else{
                inner += '<td>'+ TimeUtil.longMsTimeConvertToDateTime(item['project_start_time']) + '<br/>' + TimeUtil.longMsTimeConvertToDateTime(item['project_end_time']) + '</td>';
            }*/
            inner += "<td>" + TimeUtil.longMsTimeConvertToDateTime(item['project_start_time']) + "<br>" + TimeUtil.longMsTimeConvertToDateTime(item['project_end_time']) + "</td>";

            inner += "<td>" + item['person_count'] + "</td>";
            inner += "<td>" + Enum.projectStatus(item['project_status']) + "</td>";
            inner += "<td>" + item['create_user'] + "</td>";
            inner += "<td>" + TimeUtil.longMsTimeConvertToDateTime(item['create_time']) + "</td>";
            inner += "<td>";
            inner += '<a  onclick=\"admin_index.show_info(\'' + item.id + '\',\'' + item.project_mode + '\');\" class=\"a a-info\">详情</a>';
            if($("#company_id").val()==item['company_id']){
                if((!item['dept_id'] && admin_index.deptId == $("#company_id").val()) || (item['dept_id'] && admin_index.deptId == item['dept_id'])){
                    if (item['project_mode'] == '0') {
                        if (item['project_status'] == '1') {
                            inner += '<a  onclick=\"admin_index.project_is_publish(\'' + item.id + '\',\'' + item.project_type + '\',\'' + TimeUtil.longMsTimeToDateTime(item.project_start_time) + '\',\'' + TimeUtil.longMsTimeToDateTime(item.project_end_time) + '\',1);\" class=\"a a-publish\">发布项目</a>';
                        }
                        if (item['project_status'] == '2') {
                            inner += '<a  onclick=\"admin_index.project_is_publish(\'' + item.id + '\',\'' + item.project_type + '\',\'' + TimeUtil.longMsTimeToDateTime(item.project_start_time) + '\',\'' + TimeUtil.longMsTimeToDateTime(item.project_end_time) + '\',2);\" class=\"a  a-close\">取消发布</a>';
                        }
                    }
                }
            }
            if (item['project_status'] == '3' || item['project_status'] == '4') {
                inner += '<a  onclick=\"admin_index.show_process(\'' + item.id + '\', \'' + item.project_type + '\');\" class=\"a  a-view\">查看进度</a>';
            }
            if (admin_index.isExportExam(item['project_type'], item['project_status'])) {
                inner += '<a  onclick=\"admin_index.exportExamInfo(\'' + item.id + '\');\" class=\"a  a-info\">导出试卷</a>';
            }
            if(item['person_count'] != 0){
                inner += '<a  onclick=\"admin_index.exportPerson(\'' + item.id + '\');\" class=\"a  a-view\">导出人员</a>';
            }
            if (item['project_status'] == '3' || item['project_status'] == '4'  ) {
                if (permissionList.indexOf('admin:exportStudyTime')!=-1) {
                    inner += '<a  onclick=\"admin_index.projectTimePrint(\'' + item.id + '\',\'' + item.person_count + '\');\" class=\"a  a-view\">批量打印学时</a>';
                }
            }
            inner += "</td>";
            inner += "</tr>";
        }
        return inner;
    }
};

admin_index.projectTimePrint = function (project_id,personCount) {
    if (personCount==0){
        layer.msg("该项目没学员参加，不能打印！")
        return;
    }else {
        var printTemplateJson = print_template__admin_json;
        var editLayer = "<div id='addLayer' style='padding-left: 20px;font-size: 20px;'>";
        editLayer += "<div style='line-height: 40px;' id='template'>";
        for (var i = 0; i < printTemplateJson.length; i++) {
            editLayer += "<label style='cursor: pointer;'> <input type='radio' ";
            if (i == 0) {
                editLayer += "checked='true'";
            }
            editLayer += " id='template' data-print-id='" + printTemplateJson[i]['id'] + "' data-print-url='" + printTemplateJson[i]['print_url'] + "'  name='template' value='" + printTemplateJson[i]['template_name'] + "'/>" + printTemplateJson[i]['template_name'] + "</label><br/>";
        }
        var pageSize = 100;
        if(personCount > pageSize){
            var maxPageNum = personCount%pageSize == 0 ? personCount/pageSize : (personCount-personCount%pageSize)/pageSize+1;
            editLayer += "<div style='font-size:16px;color:#cf5d51;line-height: 30px;width: 340px;'>";
            editLayer += "当前项目共"+personCount+"人，每页"+pageSize+"条，共"+maxPageNum+"页，导出<select id='pageNum'>";
            for(var i=1;i<=maxPageNum;i++){
                editLayer += "<option value='"+i+"'>第"+i+"页</option>";
            }
            editLayer += "</select>";
            editLayer += "</div>";
        }

        editLayer += "</div>";
        editLayer += "<div class='search-group layui-layer-close' style=' margin-top: 20px;margin-left: 80px;'><button class='btn btn-info' onclick='admin_index.selectPrintTemplate(\"" + project_id + "\",1,"+pageSize + ")' style='margin-right: 10px;'>确定</button>";
        editLayer += "<button class='btn btn-info layui-layer-close' onclick='admin_index.closePrintTemplate(1)' style=''>关闭</button></div>";
        editLayer += "</div>";
        admin_index.index = layer.open({
            type: 1,
            title: '选择模板',
            shadeClose: true, // true点击遮罩层关闭
            area: ['380px', '300px'], // 弹出层大小
            scrollbar: false, // false隐藏滑动块
            content: editLayer
        });
    }

};

// 打印进入controller将参数加密
admin_index.selectPrintTemplate = function (project_id,index, pageSize) {
    var templateObj = $("#template input:radio[name='template']:checked");
    var print_name = templateObj.attr("data-print-url");
    var id = templateObj.attr("data-print-id");
    var pageNum = $("#pageNum").val();
    if (print_name == 'default_user_info.ftl') {
        url = appPath + "/popup/exportDefaultPDF?project_id=" + $.trim(project_id) + "&print_name=" + print_name
    }else{
        if (id == '2') {
            url = appPath + "/popup/exportWaterPDF?project_id=" + $.trim(project_id) + "&print_name=" + print_name+ "&type="+id
        }else{
            url = appPath + "/popup/exportWaterPDF?project_id=" + $.trim(project_id) + "&print_name=" + print_name+ "&type="+id
        }
    }
    if(undefined != pageNum){
        url += "&pageSize="+pageSize + "&pageNum=" + pageNum;
    }
    window.open(url);
};
// 打印关闭layer弹窗
admin_index.closePrintTemplate = function (index) {
    layer.close(index);
};

/**
 * 公开项目列表
 */
admin_index.initTable_public = function (){
  var list_url = appPath + "/admin/project_public/list";
  admin_index.page1.init("public_project_form", list_url, "public_project_list", "public_project_page", 1, admin_index.page_size);
  admin_index.page1.goPage(1);
  admin_index.page1.list = function(dataList){//console.log(dataList)
    $("#public_project_list").removeClass("no");
    var inner = "", item;
    admin_index.obj = dataList;
    var len = dataList.length;
    if(len > 0 ||　admin_index.public_list_show){
        admin_index.public_list_show = true;
        $("#public_box").show();
        // 组装数据
        for(var i=0; i< len; i++) {
            item = dataList[i];
            inner += "<tr>";
            inner += "<td>" +(i+1)+ "</td>";
            inner += "<td id=\'pan_varProjectName + item['id']\'><span class=\"tooltip\" data-length='30'>" + item['project_name'] + "</span></td>";
            inner += "<td>" + Enum.projectType(item['project_type']) + "</td>";

            var projectType = item['project_type'];
            var person_count = item['person_count'];
            var project_status = Number(item['project_status']);
            var ignoreVal = $("#public_ignore").val();
            // if(projectType == '3'){
            //     inner += '<td>'+ TimeUtil.longMsTimeToDateTime3(item['project_start_time']) + '<br/>' + TimeUtil.longMsTimeToDateTime3(item['project_end_time']) + '</td>';
            // }else{
            // }
            inner += '<td>' + TimeUtil.longMsTimeConvertToDateTime(item['project_start_time']) + '<br/>' + TimeUtil.longMsTimeConvertToDateTime(item['project_end_time']) + '</td>';
            // inner += "<td>" + project_time_format(item['project_start_time']) + "<br>" + project_time_format(item['project_end_time']) + "</td>";

            inner += "<td>" + person_count + "</td>";
            inner += "<td>" + Enum.projectStatus(project_status) + "</td>";
            inner += "<td>" + item['create_user'] + "</td>";
            inner += "<td>" + TimeUtil.longMsTimeConvertToDateTime(item['create_time']) + "</td>";
            inner += "<td>";
            if (ignoreVal === "0") {
                inner += '<a  onclick=\"admin_index.show_info(\'' + item.id + '\',\'' + item.project_mode + '\');\" class=\"a a-info\">详情</a>';
                if (project_status == '3' || project_status == '4') {
                    inner += '<a  onclick=\"admin_index.show_process_public(\'' + item.id + '\', \'' + item.project_type + '\');\" class=\"a  a-view\">查看进度</a>';
                }
                if(person_count != 0){
                    inner += '<a  onclick=\"admin_index.exportPerson(\'' + item.id + '\');\" class=\"a  a-info\">导出人员</a>';
                }
                if (project_status != '4') {
                    inner += '<a  onclick=\"admin_index.user_manager(\'' + item.id + '\');\" class=\"a a-view\">人员管理</a>';
                    inner += '<a  onclick=\"admin_index.sign_up(\'' + item.id + '\',\'' + item.project_type + '\');\" class=\"a a-publish\">报名</a>';
                } else {
                    inner += '<a   class=\"a \">人员管理</a>';
                    inner += '<a   class=\"a \">报名</a>';

                }
                if (person_count == "0" && project_status != '4') {

                    inner += '<a  onclick=\"admin_index.ignore(\'' + item.id + '\',1);\" class=\"a a-publish\">忽略</a>';
                } else {
                    inner += '<a   class=\"a\">忽略</a>';
                }
            } else {
                inner += '<a  onclick=\"admin_index.show_info(\'' + item.id + '\',\'' + item.project_mode + '\');\" class=\"a a-info\">详情</a>';
                inner += '<a  onclick=\"admin_index.ignore(\'' + item.id + '\',0);\" class=\"a a-publish\">恢复</a>';
            }
            inner += "</td>";
            inner += "</tr>";
        }
    }else{
        admin_index.public_list_show = false;
        $("#public_box").hide();
    }
    return inner;
  }
};
//忽略 --- 可参与
admin_index.ignore = function (projectId, ignore) {
    var companyId = $("#public_company_id").val();
    if (ignore == 1) {
        layer.confirm("您是否确认忽略此项目,一旦忽略,贵单位的所有学员将不能参与该项目?", {icon: 3}, function (index) {
            ignoreAjax(companyId, projectId, ignore);
            layer.close(index);
        }, function (index) {
            layer.close(index);
            return
        });
    }else{
        ignoreAjax(companyId, projectId, ignore);
    }

}

function ignoreAjax(companyId, projectId, ignore) {
    //更新数据
    var url = appPath + "/admin/project_private/list_item/ignore";
    var params = "company_id=" + companyId + "&project_id=" + projectId + "&ignore=" + ignore;
    $.ajax({
        url: url,
        data: params,
        type: "post",
        dataType: "json",
        success: function (result) {
            if (result.code == "10000") {
                admin_index.initTable_public();
            } else {
                layer.msg(result.message);
            }
        }
    });
}

//忽略-参与选择框变化事件
$("#public_project_form").on("change", "#public_ignore", function () {
    admin_index.initTable_public();
});

//项目状态-参与选择框变化事件
$("#public_project_form").on("change", "#public_type_click", function (e,index) {
    $("#public_project_status").val($("#public_type_click").val());
    admin_index.initTable_public();
});

//项目状态-参与选择框变化事件
$("#private_project_form").on("change", "#private_type_click", function (e,index) {
    $("#project_status").val($("#private_type_click").val());
    admin_index.initTable();
});



/*详情*/
admin_index.show_info = function (projectId, projectMode) {
   // window.location.href = appPath + "/admin/project/proManagerInfo?projectId=" + projectId + "&projectMode=" + projectMode + "&type=index";
window.open(appPath + "/admin/project/proManagerInfo?projectId=" + projectId + "&projectMode=" + projectMode + "&type=index","_blank");
}

/*查看进度(企业项目)*/
admin_index.show_process = function (projectId, projectType) {
   // window.location.href = appPath + "/admin/project/proManagerProcess?projectId=" + projectId + "&projectType=" + projectType;
    window.open(appPath + "/admin/project/proManagerProcess?projectId=" + projectId + "&projectType=" + projectType,"_bank");
}

/*查看进度（公开项目）*/
admin_index.show_process_public = function (projectId, projectType) {
    window.open(appPath + "/admin/project/pubProjectProcess?projectId=" + projectId + "&projectType=" + projectType);
}

/**
 * 报名弹窗
 * @param projectId
 * @param projectType
 */
admin_index.sign_up = function (projectId, projectType) {
    // 调用选择培训人员弹窗
    layer.open({
        type: 2,
        title: '选择报名人员',
        area: ['1200px', '80%'],		//弹出层大小
        scrollbar: false,				//false隐藏滑动块
        content: [appPath + '/popup/userSignUp?projectId=' + projectId + "&projectType=" + projectType + "&companyId=" + $("#company_id").val(), 'yes'],
        end: function () {
            admin_index.initTable_public();
        }
    });
}

/**
 * 人员管理弹窗
 * @param projectId
 * @param projectType
 */
admin_index.user_manager = function (projectId) {
    layer.open({
        type: 2,
        title: '人员管理',
        area: ['1000px', '80%'],		//弹出层大小
        scrollbar: false,				//false隐藏滑动块
        content: [appPath + '/popup/userManager?projectId=' + projectId, 'yes'],
        end: function () {
            admin_index.initTable_public();
        }
    });
}

/*取消或者发布项目*/
admin_index.project_is_publish = function (id, projectType, startTime, endTime, createType, projectStatus) {
    var url = "/admin/project/proManagerPublish";
    var param = {
        'id': id,
        'projectType': projectType,
        'startTime': startTime,
        'endTime': endTime,
        'type': createType
    }
    if (createType == 1) {
        layer.confirm("确定要发布该项目吗?", {icon: 3}, function () {
            $.ajax({
                url: appPath + url,
                type: "POST",
                cache: false,
                async: false,
                dataType: "json",
                data: param,
                success: function (result) {
                    if (result.code == '10000' && result.result == null) {
                        admin_index.initTable();
                        layer.msg("发布成功", {time: 1000});
                    } else {
                        layer.alert(result.result);
                    }
                }
            });
        });
    }
    if (createType == 2) {
        layer.confirm("确定要取消发布该项目吗?", {icon: 3}, function () {
            $.ajax({
                url: appPath + url,
                type: "POST",
                cache: false,
                async: false,
                dataType: "json",
                data: param,
                success: function (result) {
                    if (result.code == '10000') {
                        admin_index.initTable();
                        layer.msg("取消发布成功", {time: 1000});
                    } else {
                        layer.msg("取消发布失败");
                    }
                }
            });
        });
    }
    if (createType == 3) {
        $.ajax({
            url: appPath + "/admin/project/proManagerPublish",
            type: "POST",
            cache: false,
            async: false,
            dataType: "json",
            data: {'id': id, 'type': createType, 'projectStatus': projectStatus},
            success: function (result) {

            }
        });
    }
}

/*点击事件*/
admin_index.click = function () {
    //企业项目搜索
    $("#search").click(function () {
        $("#project_name").val($.trim($("#project_name").val()));
        admin_index.initTable();
    });
    //企业项目全部
    $("#search_all").click(function () {
        $("#datBeginTime").val("");
        $("#datEndTime").val("");
        $("#project_name").val("");
        $("#projectStatus").val("");
        $("#private_type_click").val("");
        //$(".status").removeClass("active");
        $("#private_clickAll").trigger("click");
    });

    //公开项目搜索
    $("#public_search").click(function () {
        $("#project_name").val($.trim($("#project_name").val()));
        admin_index.initTable_public();
    });
    //公开项目全部
    $("#public_search_all").click(function () {
        $("#public_datBeginTime").val("");
        $("#public_datEndTime").val("");
        $("#public_project_name").val("");
        $("#public_projectStatus").val("");
        $("#public_ignore").val("0");
        $("#public_type_click").val("");
        //$(".status public").removeClass("active");
        $("#public_clickAll").trigger("click");
    });

    $(".status").click(function () {
        var $this = $(this);
        var target = $this.parents('.status_flag');
        var id = target.attr('id');
        if (id === 'public') {
            $("#public_train_type").val($($this).attr("public_train_type"));
            $(this).addClass("active").siblings('.status').removeClass('active');
            admin_index.initTable_public()
        } else {
            $("#train_type").val($($this).attr("train_type"));
            $(this).addClass("active").siblings('.status').removeClass('active');
            admin_index.initTable();
        }
    });

}

admin_index.project_type_2_str = function (project_type) {
    if (!project_type) return "";
    switch (project_type) {
        case '1':
            return '培训';
            break;
        case '2':
            return '练习';
            break;
        case '3':
            return '考试';
            break;
        case '4':
            return '培训、练习';
            break;
        case '5':
            return '培训、考试';
            break;
        case '6':
            return '练习、考试';
            break;
        case '7':
            return '培训、练习、考试';
            break;
        default :
            '';
    }
};

admin_index.project_status_2_str = function (project_status) {
    if (!project_status) return "";
    switch (project_status) {
        case '1':
            return "<span class=\"text-red\">" + "未发布" + "</span>";
            break;
        case '2':
            return "<span class=\"text-gray\">" + "未开始" + "</span>";
            break;
        case '3':
            return "<span class=\"text-green\">" + "进行中" + "</span>";
            break;
        case '4':
            return "<span class=\"text-gray\">" + "已结束" + "</span>";
            break;
        default :
            '';
    }

};

// 判断是否可导出试卷(未开始、进行中并且含有考试项目)
admin_index.isExportExam = function (projectType, projectStatus) {
    if ('2' == projectStatus || '3' == projectStatus) {
        if ('3' == projectType || '5' == projectType || '6' == projectType || '7' == projectType) {
            return true;
        }
    }
    return false;
};

admin_index.exportExamInfo = function(projectId){
    // 查询项目下的角色以便选择导出
    $.ajax({
        url: appPath + '/admin/project/projectRole',
        type: "POST",
        async: false,
        data:{"projectId":projectId},
        success: function (data) {
            var list = data.result;
            var len = list.length;
            // 如果只有一个角色就直接导出，不用选择角色导出
            if(1 == len){
                admin_index.exportPaper(projectId,list[0].roleId);
            }else{
                var editLayer = "<div id='addLayer' style='padding-left: 20px;font-size: 20px;'>";
                editLayer +="<div style='line-height: 40px;'>";
                for(var i=0;i<len;i++){
                    if("-1" == list[i].roleId){
                        continue;
                    }
                    editLayer +=  "<label style='cursor: pointer;'> <input type='radio' ";
                    if(i == 0){
                        editLayer += "checked='true'";
                    }
                    editLayer += " class='template'   name='template' value='" + list[i]['roleId'] + "'/>&nbsp;&nbsp;" + list[i]['roleName'] + "</label><br/>";
                }
                editLayer += "</div>";
                editLayer += "<div class='search-group layui-layer-close' style=' margin-top: 60px;margin-left: 80px;'><button class='btn btn-info' onclick='admin_index.selectRole(\""+ projectId +"\",1)' style='margin-right: 10px;'>确定</button>";
                editLayer += "<button class='btn btn-info layui-layer-close' onclick='admin_index.closeRoleTemplate(1)' style=''>关闭</button></div>";
                editLayer += "</div>";
                admin_index.index = layer.open({
                    type: 1,
                    title: '选择角色导出',
                    shadeClose: true, // true点击遮罩层关闭
                    area: ['380px', '280px'], // 弹出层大小
                    scrollbar: false, // false隐藏滑动块
                    content: editLayer
                });


            }

        }
    });

};
// 打印进入controller将参数加密
admin_index.selectRole = function (project_id,index) {

    var roleId = $("#addLayer input:radio[name='template']:checked").val();
    admin_index.exportPaper(project_id,roleId);
    layer.close(index);
};
// 打印关闭layer弹窗
admin_index.closeRoleTemplate = function (index) {
    layer.close(index);
};

// 导出试卷
admin_index.exportPaper = function (projectId,roleId) {

    var exam_no = '';
    // var winopn = window.open("", "project_paper");
    // //如果ajax响应时间过长，就给个提示
    // winopn.document.write('<style>body{margin:0;padding:0;background: #e8edf0;overflow: hidden;}</style><img src="' + resourcePath +     //'static/global/images/import_paper.png" style="width:100%;height:auto;margin-top:9%;"/>');
    // // 循环请求试卷编号，生成试卷的时间未定所以要轮询请求直到拿到exam_no
    while ("" == exam_no) {
        var url = appPath + '/admin/exportProjectPaper';
        var param = {"projectId": projectId, "roleId": roleId};
        var data = admin_index.ajax(url, param);
        var code = data['code'];
        if (code == '10000') {
            var result = data['result'];
            if (result && result != '') {
                exam_no = result;
            }
        } else {
            layer.alert("网络异常", {icon: 3});
            break;
        }
    }
    setCookie('exam_no' + projectId, exam_no);
    // window.setTimeout(function () {
    //     var url = appPath + "/admin/exportExam?examNo=" + exam_no + "&projectId=" + projectId + "&roleId=" + roleId+ "&isCenterTrain=" + "0";
    //     winopn.location = url;
    // }, 2500);
    window.location.href = appPath +  "/admin/exportExam?examNo=" + exam_no + "&projectId=" + projectId + "&roleId=" + roleId+ "&isCenterTrain=" + "0";
};


admin_index.ajax = function (url, param) {
    var result = '';
    $.ajax({
        url: url,
        async: false,
        type: 'post',
        data: param,
        success: function (data) {
            result = data;
        }
    });
    return result;
}

// 项目自定义排序
admin_index.sort = function (value, obj) {
    $("#sortBy").val(value);
    var order = obj.className
    if (order == 'sort asc') {
        $("#descAsc").val('DESC')
    } else {
        $("#descAsc").val('ASC')
    }
    // 刷新列表
    admin_index.initTable();
}


// 七天之内,需要发布的提示
admin_index.handlerPublish = function () {
    if ("1" == getCookie("publishFlag")) return;
    $.ajax({
        url: appPath + "/admin/message_notice",
        type: "POST",
        cache: false,
        async: false,
        dataType: "json",
        success: function (data) {
            var code = data.code;
            var result = data.result;
            if ( code == '10000') {
                var unPublishProjectCount = result.unPublishProjectCount;
                var messageCount = result.messageCount;
                if(0 == (parseInt(unPublishProjectCount) + parseInt(messageCount))){
                    return;
                }
                setCookie("publishFlag", "1");
                var html = "<div class='box' id='addLayer' style='padding-left: 20px;font-size: 14px;width: 300px;'>";
                html += "<div class='search-group' style=' margin-top: 0px;margin-left: -20px;'>";
                if(0 != parseInt(messageCount) ){
                    html += "<div style=\"font-size: 15px;margin-bottom: 12px;font-weight: 700;color: rgb(221, 25, 25);\">待查看通知信息&nbsp;&nbsp;&nbsp;";
                    html += '<a href="'+ appPath +'/popup/msg" >'+ parseInt(messageCount) +'</a>'
                    html += "&nbsp;&nbsp;个</div>"
                }
                if(0 != parseInt(unPublishProjectCount) ){
                    html += "<div style=\"font-size: 15px;font-weight: 700;color: rgb(221, 25, 25);\">项目发布提醒&nbsp;&nbsp;&nbsp;";
                    html += "<a href=''+ appPath +'/admin' >"+ parseInt(unPublishProjectCount) +"</a>"
                    html += "&nbsp;&nbsp;个</div>"
                }

                html += "</div></div>";
                layer.open({
                    title: '提示',
                    closeBtn: 0,
                    content: html,
                    scrollbar: false,
                    btn: ['知道了'],
                    yes: function (index) {
                        layer.close(index);
                        //location.href="#private_project_list";  //兼容ie跳转
                        //$("html,body").animate({scrollTop: $("#div_wjs_project").offset().top}, 1000);
                    }
                });



            }
        }
    });


};


/**
 * 导出人员
 * @param projectId
 */
admin_index.exportPerson = function (projectId) {
    var message = "<div style='padding:50px;line-height:22px;background-color:#393D49;color:#fff;font-weight:300;font-size: 15px;'> 请选择导出模板 &nbsp;&nbsp;&nbsp;&nbsp;</div>";
    layer.open({
        type:1,
        title: false, // 不显示标题栏
        closeBtn: true,
        area: "300px",
        shade: 0.3,
        id: "layer-submit-exam-paper", // 设置id, 防止重复弹出
        resize: false,
        btn:['通用导出模板','账号导出模板'],
        btnAlign: "c",
        moveType: 1,
        content: message,
        btn1: function(index) {
            layer.close(index);
            //window.open(appPath + "/admin/personExport?projectId=" + projectId + "&exportType=2");
            window.open(appPath + "/admin/dossier/project/export?project_id=" + projectId );
        },
        btn2: function(index) {
            layer.close(index);
            window.open(appPath + "/admin/personExport?projectId=" + projectId + "&exportType=1");
        }
    });

};




// 培训政策须知
admin_index.trainPolicyNotes = function () {
    if($("#trainPolicyNotes").length == 0){
        return
    }
    if ("1" == getCookie("trainPolicyNotes")) return;
    $.ajax({
        url: appPath + "/admin/selectTrainPolicyList",
        type: "POST",
        cache: false,
        async: false,
        dataType: "json",
        success: function (data) {
            var code = data.code;
            var result = data.result;
            if ( code == '10000') {
                 setCookie("trainPolicyNotes", "1");
                if(result.length == 0){
                    return;
                }
                var html = '<div>';
                   for(var i = 0; i < result.length;i++){
                       html += '<div style="margin-top: 15px;margin-right: 30px;">';
                       html += '<h2 style="margin-left: 35px;">'+ result[i].businessName +'</h2>';
                       html += '<div style="margin-top: 15px;margin-bottom: 15px; margin-left: 70px;line-height: 25px;font-size: 16px;font-family: 微软雅黑;"><span style="display:block;text-indent: 2em;">'+ result[i].content +'</span></div>';
                       html += '</div>';
                   }
                    html += '</div>';

                layer.open({
                    type: 1,
                    skin: 'layui-layer-rim',
                    title: '培训政策须知',
                    shadeClose: true,
                    shade: 0.1,
                    area: ['940px', '600px'],
                    content: html //iframe的url
                });



            }
        }
    });


};


// 培训政策须知
admin_index.trainWarnNotes = function () {

    var companyId = $("#companyId").val();
    var year = new Date().getFullYear();
    var month = new Date().getMonth() + 1;
    month = month < 10 ? "0" + month : month;
    var param = {
        "companyId":companyId,
        "month": year + "" + month
    }
    $.ajax({
        url: appPath + "/admin/trainNotes/getTrainWarnMessageInfo",
        type: "POST",
        data:param,
        dataType: "json",
        success: function (data) {
            var code = data.code;
            var result = data.result;
            if ( code == '10000') {
                var month = result.month;
              if(!month){
                  $("#trainWarn").addClass("no");
                  return;
              }

            var certificate_count = result.certificate_count;
            var  have_certificate_count =  result.have_certificate_count;
            var plan_completion_count = result.plan_completion_count;
            var plan_count = result.plan_count;
            var standard_user_count = result.standard_user_count;
            var  three_train_count = result.three_train_count
            var train_user_count = result.train_user_count;
            var user_count = result.user_count;
            var year_studytime = result.year_studytime;

            /*if(0 != year_studytime){
                year_studytime = (parseInt(year_studytime)/3600).toFixed(2);
            }*/
            // 年度已培训学时
            $("#yearStudyTime").text(TimeUtil.getHouAndMinAndSec(year_studytime));

            // 月度学时达标率
            var trainCompleteRate = '0%';
            // 培训率
            var trainRate = '0%';
            if(0 != user_count){
                trainCompleteRate =  (parseInt(standard_user_count)/parseInt(user_count)).toFixed(2) *100 + "%";
                trainRate =  (parseInt(train_user_count)/parseInt(user_count)).toFixed(2) *100 + "%";
            }
            $("#trainCompleteRate").text(trainCompleteRate);
            $("#trainRate").text(trainRate);

            // 计划完成率
            var trainPlanRate = '0%';
            if(0 != plan_count){
                trainPlanRate =  (parseInt(plan_completion_count)/parseInt(plan_count)).toFixed(2) *100 + "%";
            }
            $("#trainPlanRate").text(trainPlanRate);

            // 持证率
            var certificateRate = '0%';
            if(0 != certificate_count){
                certificateRate = (parseInt(have_certificate_count)/parseInt(certificate_count)).toFixed(2) *100 + "%";
            }
            $("#cerificateRate").text(certificateRate);

            // 三级培训人次
            $("#trainUserCount").text(three_train_count);
            }
        }
    });


};
